<template>
  <div class="manager-home">
    <!-- 欢迎卡片 -->
    <el-card class="welcome-card" shadow="never">
      <div class="welcome-content">
        <div class="user-info">
          <el-avatar :size="60" :icon="UserFilled" />
          <div class="user-details">
            <h2>欢迎回来，{{ managerName }}</h2>
            <p>今天是 {{ currentDate }}，祝您工作愉快！</p>
          </div>
          <el-button 
            :icon="Refresh" 
            circle 
            size="small"
            :loading="isLoading"
            @click="refreshData"
            title="刷新数据"
          />
        </div>
        <div class="quick-stats">
          <div class="stat-item">
            <div class="stat-number">{{ todayVisits }}</div>
            <div class="stat-label">今日拜访</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ monthlyVisits }}</div>
            <div class="stat-label">本月累计拜访</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ pendingVisits }}</div>
            <div class="stat-label">待拜访客户</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ visitProgress }}%</div>
            <div class="stat-label">客户拜访进度</div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 主要功能模块 -->
    <el-card class="functions-card" shadow="never">
      <template #header>
        <div class="card-header">
          <el-icon><Grid /></el-icon>
          <span>主要功能</span>
        </div>
      </template>

      <div class="function-grid">
        <div
          v-for="func in mainFunctions"
          :key="func.name"
          class="function-item"
          @click="$router.push(func.path)"
        >
          <div class="function-icon" :style="{ backgroundColor: func.color }">
            <el-icon :size="24">
              <component :is="func.icon" />
            </el-icon>
          </div>
          <div class="function-info">
            <div class="function-name">{{ func.name }}</div>
            <div class="function-desc">{{ func.desc }}</div>
            <div class="function-count">{{ func.count }}</div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 快捷操作 -->
    <el-card class="quick-actions-card" shadow="never">
      <template #header>
        <div class="card-header">
          <el-icon><Lightning /></el-icon>
          <span>快捷操作</span>
        </div>
      </template>

      <el-row :gutter="12">
        <el-col :span="12">
          <el-button
            type="primary"
            size="large"
            class="action-btn"
            @click="$router.push('/work-log')"
          >
            <el-icon><EditPen /></el-icon>
            <span>记录日志</span>
          </el-button>
        </el-col>
        <el-col :span="12">
          <el-button
            type="success"
            size="large"
            class="action-btn"
            @click="$router.push('/task-reminder')"
          >
            <el-icon><Bell /></el-icon>
            <span>任务提醒</span>
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 最近活动 -->
    <el-card class="recent-activities-card" shadow="never">
      <template #header>
        <div class="card-header">
          <el-icon><Clock /></el-icon>
          <span>最近活动</span>
        </div>
      </template>

      <el-timeline v-if="recentActivities.length > 0">
        <el-timeline-item
          v-for="activity in recentActivities"
          :key="activity.id"
          :timestamp="activity.time"
          :type="activity.type"
        >
          <div class="activity-content">
            <div class="activity-title">{{ activity.title }}</div>
            <div class="activity-desc">{{ activity.desc }}</div>
          </div>
        </el-timeline-item>
      </el-timeline>
      <div v-else class="empty-state">
        <el-empty description="暂无最近活动"></el-empty>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onActivated, markRaw } from 'vue'
import {
  UserFilled, Grid, Lightning, EditPen, Bell, Clock, Refresh,
  User, Phone, Star, TrendCharts, Avatar, Document
} from '@element-plus/icons-vue'
import { trpc } from '@/utils/trpc'
import { AuthUtils } from '@/utils/auth'
import { ElMessage } from 'element-plus'

// 用户信息
const managerName = ref('')
const currentDate = computed(() => {
  return new Date().toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    weekday: 'long'
  })
})

// 统计数据（真实接口填充）
const todayVisits = ref(0)
const monthlyVisits = ref(0)
const pendingVisits = ref(0)
const visitProgress = ref(0)
const totalClients = ref(0)
const serviceProgress = ref<{[key: string]: number}>({})

// 加载状态
const isLoading = ref(false)

// 服务项目图标和颜色映射
const serviceIconMap: Record<string, any> = {
  '客户拜访': markRaw(User),
  '诚信五化建设': markRaw(TrendCharts),
  '客户评价': markRaw(Star),
  '满意度调查': markRaw(Phone),
  '四员协同': markRaw(Avatar),
  '工作日志': markRaw(Document),
  // 可以根据需要添加更多映射
}

const serviceColorMap: Record<string, string> = {
  '客户拜访': '#409EFF',
  '诚信五化建设': '#67C23A',
  '客户评价': '#E6A23C',
  '满意度调查': '#F56C6C',
  '四员协同': '#909399',
  '工作日志': '#606266',
  // 默认颜色轮换
}

const defaultColors = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399', '#606266', '#6F7AD3', '#FF7875']

// 主要功能模块（动态加载）
const mainFunctions = ref<any[]>([])

// 获取服务项目的图标
function getServiceIcon(serviceName: string) {
  return serviceIconMap[serviceName] || markRaw(Document)
}

// 获取服务项目的颜色
function getServiceColor(serviceName: string, index: number) {
  return serviceColorMap[serviceName] || defaultColors[index % defaultColors.length]
}

// 生成服务项目的路由路径
function getServicePath(serviceName: string) {
  const pathMap: Record<string, string> = {
    '客户拜访': '/client-visit',
    '诚信五化建设': '/integrity-building',
    '客户评价': '/client-evaluation',
    '满意度调查': '/satisfaction-survey',
    '四员协同': '/team-collaboration',
    '工作日志': '/work-log'
  }
  return pathMap[serviceName] || `/service/${encodeURIComponent(serviceName)}`
}

// 最近活动（从工作日志构造）
const recentActivities = ref<any[]>([])

async function loadDashboard() {
  const user = AuthUtils.getUser<any>()
  if (!user?.id) return

  isLoading.value = true
  try {
    // 1) 个人信息
    const profile = await trpc.auth.profile.query({ managerId: user.id })
    if (profile?.success) {
      managerName.value = profile.data.manager.fullName || profile.data.manager.username
    }

  // 2) 动态加载服务项目列表
  try {
    const serviceList = await trpc.service.list.query({ pageSize: 100 })
    if (serviceList?.success) {
      const services = serviceList.data.data || serviceList.data || []
      
      // 构建主要功能模块
      const dynamicFunctions = services.map((service: any, index: number) => ({
        id: service.id,
        name: service.serviceName,
        desc: service.description || `${service.serviceName}服务记录`,
        icon: getServiceIcon(service.serviceName),
        color: getServiceColor(service.serviceName, index),
        path: getServicePath(service.serviceName),
        count: ''
      }))
      
      // 添加工作日志功能（如果不存在）
      const hasWorkLog = dynamicFunctions.some((f: any) => f.name === '工作日志')
      if (!hasWorkLog) {
        dynamicFunctions.push({
          id: 'work-log',
          name: '工作日志',
          desc: '日常工作记录',
          icon: markRaw(Document),
          color: '#606266',
          path: '/work-log',
          count: ''
        })
      }
      
      mainFunctions.value = dynamicFunctions
    }
  } catch (error) {
    console.error('加载服务项目失败:', error)
    // 降级到默认功能
    mainFunctions.value = [
      { name: '工作日志', desc: '日常工作记录', icon: markRaw(Document), color: '#606266', path: '/work-log', count: '' }
    ]
  }

  // 2) 获取该客户经理分配的总客户数
  try {
    const managerClientsRes = await trpc.manager.clients.query({
      managerId: user.id,
      page: 1,
      pageSize: 1 // 只需要总数，不需要具体数据
    })
    if (managerClientsRes?.success) {
      totalClients.value = managerClientsRes.data.pagination?.total || 0
    }
  } catch (error) {
    console.error('获取客户总数失败:', error)
  }

  // 3) 获取本月工作日志数据，计算今日拜访和本月累计拜访
  const now = new Date()
  const monthStart = new Date(now.getFullYear(), now.getMonth(), 1)
  const monthEnd = new Date(now.getFullYear(), now.getMonth() + 1, 0)

  // 分页获取所有本月数据
  const allLogs: any[] = []
  let page = 1
  const pageSize = 100 // API最大限制
  let hasMore = true
  
  while (hasMore) {
    const listRes = await trpc.workLog.list.query({
      managerId: user.id,
      startDate: monthStart.toISOString(),
      endDate: new Date(monthEnd.getFullYear(), monthEnd.getMonth(), monthEnd.getDate(), 23, 59, 59, 999).toISOString(),
      page,
      pageSize
    })
    
    if (listRes?.success) {
      const logs = listRes.data.data || listRes.data || []
      allLogs.push(...logs)
      
      // 检查是否还有更多数据
      hasMore = logs.length === pageSize
      page++
    } else {
      hasMore = false
    }
  }
  
  // 使用所有获取到的日志数据进行统计
  if (allLogs.length > 0) {
    // 今日拜访 - 统计拜访的客户数，不是完成的服务项目数
    const todayStr = new Date().toISOString().slice(0, 10)
    const todayLogs = allLogs.filter((l: any) => l.completionDate?.slice(0,10) === todayStr)
    const uniqueClientsToday = new Set(todayLogs.map((l: any) => l.clientId)).size
    todayVisits.value = uniqueClientsToday
    
    // 本月累计拜访 - 统计本月拜访的不重复客户数
    const uniqueClientsThisMonth = new Set(allLogs.map((l: any) => l.clientId)).size
    monthlyVisits.value = uniqueClientsThisMonth
    
    // 计算待拜访客户数 = 总客户数 - 本月累计拜访
    pendingVisits.value = Math.max(0, totalClients.value - monthlyVisits.value)
    
    // 计算客户拜访进度 = (本月累计拜访 / 总客户数) * 100
    visitProgress.value = totalClients.value > 0 ? 
      Math.round((monthlyVisits.value / totalClients.value) * 100) : 0

    // 最近活动（按时间排序取前4条）
    const sorted = [...allLogs].sort((a: any, b: any) => new Date(b.completionDate).getTime() - new Date(a.completionDate).getTime())
    recentActivities.value = sorted.slice(0, 4).map((l: any, idx: number) => ({
      id: l.id || idx,
      title: `完成：${l.service?.serviceName || '工作'}`,
      desc: `${l.client?.clientName || ''} ${l.client?.clientCode || ''}`.trim(),
      time: new Date(l.completionDate).toLocaleString('zh-CN'),
      type: 'primary'
    }))
  }


  // 4) 各模块 count（基于动态加载的服务项目）
  try {
    const updates: any[] = []
    const progressData: {[key: string]: number} = {}
    
    // 批量处理服务统计请求
    const serviceStatPromises = mainFunctions.value
      .filter(mf => mf.id && mf.id !== 'work-log')
      .map(async (mf) => {
        try {
          const stat = await trpc.workLog.serviceStats.query({ 
            managerId: user.id, 
            serviceId: mf.id, 
            startDate: monthStart.toISOString(), 
            endDate: monthEnd.toISOString() 
          })
          return { mf, stat }
        } catch (error) {
          console.warn(`获取服务 ${mf.name} 统计失败:`, error)
          return { mf, stat: null }
        }
      })

    const serviceStatResults = await Promise.allSettled(serviceStatPromises)
    
    // 处理统计结果
    serviceStatResults.forEach((result) => {
      if (result.status === 'fulfilled') {
        const { mf, stat } = result.value
        if (stat?.success) {
          const completed = stat.data.completedCount || 0
          const target = stat.data.targetCount || stat.data.totalClients || 30 // 优先使用总客户数，否则默认30户/月
          const progress = Math.round((completed / target) * 100)
          progressData[mf.name] = progress
          
          const label = mf.name === '四员协同' ? `本月提交 ${completed} 条` : `本月完成 ${completed} 户`
          updates.push({ name: mf.name, count: label })
        }
      }
    })
    
    // 处理工作日志统计
    const workLogFunction = mainFunctions.value.find(mf => mf.name === '工作日志')
    if (workLogFunction) {
      const workDays = new Set(allLogs.map((l: any) => l.completionDate?.slice(0,10))).size
      const targetDays = Math.ceil(monthEnd.getDate() * 0.7) // 目标工作天数为当月天数的70%
      const progress = Math.round((workDays / targetDays) * 100)
      progressData[workLogFunction.name] = progress
      
      const label = `本月记录 ${workDays} 天`
      updates.push({ name: workLogFunction.name, count: label })
    }
    
    serviceProgress.value = progressData
    for (const u of updates) {
      const target = mainFunctions.value.find(m => m.name === u.name)
      if (target) target.count = u.count
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
  } catch (error) {
    console.error('加载仪表板失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    isLoading.value = false
  }
}

// 刷新数据
async function refreshData() {
  await loadDashboard()
  ElMessage.success('数据已刷新')
}

onMounted(() => {
  loadDashboard()
})

// 页面激活时自动刷新（从其他页面返回时）
onActivated(() => {
  loadDashboard()
})
</script>

<style scoped>
.manager-home {
  padding: 20px;
  padding-bottom: 80px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.welcome-card {
  margin-bottom: 20px;
}

.welcome-content {
  padding: 20px 0;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 25px;
}

.user-details h2 {
  font-size: 1.4rem;
  font-weight: 600;
  color: #333;
  margin: 0 0 5px 0;
}

.user-details p {
  color: #666;
  font-size: 0.9rem;
  margin: 0;
}

.quick-stats {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  padding: 20px;
  color: white;
}

.stat-item {
  text-align: center;
  padding: 10px;
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.1);
}

.stat-number {
  font-size: 1.5rem;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 0.75rem;
  opacity: 0.9;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #333;
}

.functions-card {
  margin-bottom: 20px;
}

.function-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 15px;
}

.function-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s;
}

.function-item:hover {
  background: #e9ecef;
  transform: translateY(-2px);
}

.function-icon {
  width: 50px;
  height: 50px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.function-info {
  flex: 1;
}

.function-name {
  font-size: 1rem;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.function-desc {
  font-size: 0.8rem;
  color: #666;
  margin-bottom: 4px;
}

.function-count {
  font-size: 0.75rem;
  color: #999;
}

.quick-actions-card {
  margin-bottom: 20px;
}

.action-btn {
  width: 100%;
  height: 60px;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.action-btn .el-icon {
  font-size: 20px;
}

.recent-activities-card {
  margin-bottom: 20px;
}

.activity-content {
  padding-left: 10px;
}

.activity-title {
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.activity-desc {
  font-size: 0.9rem;
  color: #666;
}
</style>
